<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-11-10 00:25:34
component:     operation
Copyright © YourCompanyName All rights reserved
-->
<template>
  <el-dialog
    :destroy-on-close="true"
    :title="dialogTitle"
    v-model="isVisible"
    @close="handleClose"
    width="1200px"
  >
    <el-card>
      <div style="display: flex; flex-direction: row; align-items: center">
        <FormComponent ref="formRef" :config="formConfig" />
        <div
          style="
            margin-left: 36px;
            margin-bottom: 38px;
            display: flex;
            flex-direction: row;
            align-items: center;
          "
        >
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />重置</el-button>
          <el-form
            :disabled="disabled"
            style="margin-left: 12px"
            :model="isListedFormData"
            ref="isListedForm"
          >
            <el-form-item
              :rules="[{ required: true, message: '请选择是否上架', trigger: 'change' }]"
              style="margin-bottom: 0"
              prop="isListed"
              label="是否上架"
            >
              <el-radio-group v-model="isListedFormData.isListed">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
            </el-form-item></el-form
          >
        </div>
      </div>
      <el-alert :title="'已选择 ' + selectedCount + ' 项'" type="success" />
      <el-table
        ref="tableRef"
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        :data="list"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 + (queryParams.pageNo - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="酒水编号" prop="drinkCode" />
        <el-table-column label="酒水名称" prop="drinkName" />
        <el-table-column label="价格" prop="price" />
        <el-table-column label="瓶数" prop="bottleCount" />
        <el-table-column label="包裹数" prop="packageCount" />
        <el-table-column label="库存数量" prop="stock" />
        <el-table-column label="奖金栏" prop="bonusRule" />
        <el-table-column label="是否上架" prop="isListed">
          <template #default="scope">
            <span>{{ scope.row.isListed ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <!-- 新增的编辑单元格 -->
        <el-table-column label="数量" width="200">
          <template #default="scope">
            <el-input-number value v-model="selectedQuantities[scope.row.id]" :min="1" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- <Index /> -->
    <template v-if="!disabled" #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handleFormSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { MODALTYPE } from '@/types/ref'
import { ref, watch, defineProps, defineEmits } from 'vue'
import FormComponent from '@/components/FormComponent/index.vue'
import {
  createPackageManagement,
  getPackageManagement,
  updatePackageManagement
} from '@/api/drinks/set-menu'
import { DrinkItem, pageDrinkInventory } from '@/api/drinks/drinks-put'
import { ElTable, FormInstance } from 'element-plus'
interface Props {
  visible: boolean
  modalType: MODALTYPE
  id?: string
}
const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'refreshTable'): void
}>()
const initTableData = ref<{ drinkId: number; num: number }[]>([])

// ==================== 表格搜索表单  ====================
const formRef = ref<InstanceType<typeof FormComponent>>()
const formConfig = [
  {
    label: '酒水编号',
    prop: 'drinkCode',
    type: 'input',
    options: { placeholder: '请输入酒水编号' }
  },
  {
    label: '酒水名称',
    prop: 'drinkName',
    type: 'input',
    options: { placeholder: '请输入酒水名称' }
  }
]
// --------------------  表格  ---------------------
const tableRef = ref<InstanceType<typeof ElTable>>()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<DrinkItem[]>([]) // 列表的数据
// 分页
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

// 定义选中项数量的状态
const selectedCount = ref(0)
const selectedQuantities = reactive<Record<string, number>>({})
const selectId = ref<number[]>([])
// 处理选择变化的函数
const handleSelectionChange = (selection: any[]) => {
  selectId.value = selection.map((item) => item.id)
  selectedCount.value = selection.length // 更新选中项的数量
}
// 生成包含 drinkId 和 num 的数组
const selectedItems = computed(() => {
  return selectId.value.map((id) => ({
    drinkId: id,
    num: selectedQuantities[id] || 1
  }))
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await pageDrinkInventory({
      ...queryParams,
      ...formRef.value?.formData,
      isListed: '1'
    })
    list.value = data.list
    total.value = data.total
  } catch (e) {
    console.error(e)
    loading.value = false
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  formRef.value?.handleReset()
  handleQuery()
}

/** 初始化 */
onMounted(() => {
  getList()
})

const getRowKey = (row: any) => {
  return row.id
}

watch(
  [() => props.modalType, () => initTableData, () => list.value],
  ([newModalType, newTableData, newList]) => {
    tableRef?.value?.clearSelection()
    if (
      newModalType === MODALTYPE.EMIT ||
      (newModalType === MODALTYPE.DETAIL && newTableData.value.length > 0)
    ) {
      const filteredArray = newList.filter((item) =>
        newTableData.value.some((el) => el.drinkId === item.id)
      )
      filteredArray.forEach((item) => {
        tableRef?.value?.toggleRowSelection(item, true)
      })
      newTableData.value.forEach((item) => {
        selectedQuantities[item.drinkId] = item.num
      })
      selectId.value = newTableData.value.map((item) => item.drinkId)
    }
  },
  { deep: true }
)
// ==================== 表单  ====================
const isListedForm = ref<FormInstance>()
const isListedFormData = reactive<{ isListed: number | undefined }>({
  isListed: undefined
})
// 提交的函数
const handleFormSubmit = async () => {
  try {
    await isListedForm.value?.validate()
    let res
    if (props.modalType === MODALTYPE.ADD) {
      res = await createPackageManagement({
        isListed: isListedFormData.isListed,
        drinks: selectedItems.value || []
      })
    } else {
      res = await updatePackageManagement({
        isListed: isListedFormData.isListed,
        id: props.id,
        drinks: selectedItems.value || []
      })
    }
    if (res.code === 0) {
      ElMessage({
        showClose: true,
        message: '操作成功',
        type: 'success'
      })
    }
    emit('refreshTable')
    handleClose()
  } catch (e) {
    console.error(e)
  }
}
// ==================== 弹窗状态  ====================
// 局部状态变量，用于管理弹窗的可见性
const isVisible = ref<boolean>(props.visible)
// 关闭弹窗的处理函数
const handleClose = () => {
  isVisible.value = false // 设置局部状态
  emit('update:visible', false) // 通知父组件
  isListedFormData.isListed = undefined
}
// 监视 props.visible 的变化，以更新局部状态
watch(
  () => props.visible,
  (newValue) => {
    isVisible.value = newValue
  }
)
// 动态标题
const dialogTitle = computed(() => {
  switch (props.modalType) {
    case MODALTYPE.ADD:
      return '新增套餐'
    case MODALTYPE.EMIT:
      return '编辑套餐'
    case MODALTYPE.DETAIL:
      return '查看套餐详情'
    default:
      return '操作'
  }
})
// 禁用
const disabled = computed(() => props.modalType === MODALTYPE.DETAIL)
// 弹窗是新增状态数量赋值为1
watch([list, () => props.modalType, () => props.visible], async ([newList, type, newVisible]) => {
  if (newVisible && newList.length > 0 && type === MODALTYPE.ADD) {
    isListedFormData.isListed = undefined
    newList.forEach((item) => {
      selectedQuantities[item.id] = 1
    })
  }
  if (newVisible && (type === MODALTYPE.DETAIL || type === MODALTYPE.EMIT) && newList.length > 0) {
    newList.forEach((item) => {
      selectedQuantities[item.id] = 1
    })
    const res = await getPackageManagement(props.id as string)
    initTableData.value = res.drinks
    isListedFormData.isListed = res.isListed ? 1 : 0
  }
})
watch(
  () => props.visible,
  (newValue) => {
    isVisible.value = newValue
  }
)
</script>

<style scoped>
/* 您的样式 */
</style>
